package me.zhengjie.modules.system.domain

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.bean.copier.CopyOptions
import com.alibaba.fastjson.annotation.JSONField
import com.fasterxml.jackson.annotation.JsonTypeName
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.persistence.*
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
import me.zhengjie.common.base.BaseEntity
import me.zhengjie.common.utils.JacksonUtil
import org.hibernate.annotations.CreationTimestamp
import org.springframework.data.redis.core.RedisHash
import java.sql.Timestamp

/**
 * @author Kuki Wu
 * @date 2019-03-25
 */
@Entity
@Table(name = "sys_dept")
@JsonTypeName("sysdept")
@RedisHash("sysdept")
data class Dept (
    @Schema(description = "ID", hidden = true)
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "dept_id")
    var id: @NotNull(groups = [Update::class]) Long? = null,

    //@get:JsonIgnore
    @Schema(description = "角色")
    @JSONField(serialize = false)
    @ManyToMany(mappedBy = "depts")
    var roles: Set<Role>? = null,

    @Schema(description = "排序")
    var deptSort: Int? = null,

    @Schema(description = "部门名称")
    //@Column(name = "name", nullable = false)
    var name: @NotBlank String? = null,

    @Schema(description = "是否启用")
    var enabled: @NotNull Boolean? = null,

    //@Column(name = "pid", nullable = false)
    @Schema(description = "上级部门")
    var pid: @NotNull Long? = null,

    @Schema(description = "子节点数目", hidden = true)
    var subCount: Int? = 0

):BaseEntity(){
    annotation class Update

    companion object {
        fun fromJson(json: String): Dept? {
            val obj = JacksonUtil.parseObject(json, Dept::class.java)!!
            return when (obj) {
                is Dept -> obj
                else -> null
            }
        }
    }
    
    fun copy(source: Dept?) {
        BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true))
    }
}